package com.lineage.server.timecontroller.pc;

import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.thread.PcOtherThreadPool;
import com.lineage.server.world.World;
import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PcHellTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(PcHellTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 1000;
    this._timer = PcOtherThreadPool.get().scheduleAtFixedRate(this, 1000L, 1000L);
  }
  
  public void run() {
    try {
      Collection<L1PcInstance> all = World.get().getAllPlayers();
      if (all.isEmpty())
        return; 
      Iterator<L1PcInstance> iter = all.iterator();
      while (iter.hasNext()) {
        L1PcInstance tgpc = iter.next();
        int time = tgpc.getHellTime();
        if (time <= 0)
          continue; 
        time--;
        if (!tgpc.isDead())
          check(tgpc, Integer.valueOf(time)); 
        Thread.sleep(1L);
      } 
    } catch (Exception e) {
      _log.error("PC 地狱模式处理时间轴异常重启", e);
      PcOtherThreadPool.get().cancel(this._timer, false);
      PcHellTimer hellTimer = new PcHellTimer();
      hellTimer.start();
    } 
  }
  
  private static void check(L1PcInstance tgpc, Integer time) {
    if (time.intValue() > 0) {
      tgpc.setHellTime(time.intValue());
    } else {
      tgpc.setHellTime(0);
      if (tgpc.getNetConnection() != null)
        outPc(tgpc); 
    } 
  }
  
  private static void outPc(L1PcInstance tgpc) {
    try {
      if (tgpc != null)
        tgpc.endHell(); 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
}
